<?php

namespace App\Console\Commands;

use App\Models\FormInstance;
use App\Models\Teaching\TeachingSubject;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class DelReviewTeachingSubject extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'delTeachingSubject:reviewStatus';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '删除任教学科待审核状态数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info("---删除任教学科待审核状态数据,开始:".date('Y-m-d H:i:s')."---");
        $delCount = $this->taskRun();
        $this->info("---共删除".$delCount."条数据,结束:".date('Y-m-d H:i:s')."---");
    }

    private function taskRun()
    {
        $formInstance = FormInstance::where([
            'form_key'=> 'TEARRESEARCH_TEASUBJECTS_TABLE',
            'type' => 'MainForm',
            'status' => 'REVIEW'
        ])->get();
        
        $count = $formInstance->count();
        $formInstanceIds = $formInstance->pluck('id')->toArray();

        DB::beginTransaction();
        try {
            TeachingSubject::whereIn('form_instance_id', $formInstanceIds)->delete();
            FormInstance::whereIn('id', $formInstanceIds)->delete();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            $this->error($e->getMessage());
        }

        return $count;
    }

}
